package com.chukun.multi.serialthreadconfinement.reusable;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Future;

/**
 * @author chukun
 * @param <T> Serialiser 向WorkThread所提交的任务的类型
 * @param <V> service方法的返回值类型
 */
public abstract  class AbstractSerializer<T,V> {

    private final TerminatableWorkerThread<T,V> workerThread;

    public AbstractSerializer(BlockingQueue<Runnable> workQueue,TaskProcessor<T,V> taskProcessor){
        workerThread = new TerminatableWorkerThread<>(workQueue,taskProcessor);
    }

    /**
     * 留给子类实现，用于根据参数生成对应的任务实例
     * @param params
     * @return
     */
    protected abstract  T makeTask(Object ... params);

    /**
     * 该类对外暴露的服务的方法
     * @param params 参数列表
     * @return 获取任务处理的结果的Promise
     * @throws InterruptedException
     */
    protected Future<V> service(Object ... params) throws InterruptedException{
        T task = makeTask(params);
        Future<V> future = workerThread.submit(task);
        return future;
    }

    public void init(){
        workerThread.start();
    }

    public void shutdown(){
        workerThread.terminate();
    }
}
